package ch.ffhs.links_library.session;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ch.ffhs.links_library.entities.*;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.framework.EntityHome;
import org.jboss.seam.log.Log;

@Name("linkHome")
public class LinkHome extends EntityHome<Link> {

	
	private static final long serialVersionUID = -2426750073241507388L;
	
	/**
	 * This regex is used afterwards to check if the link is in a correct format
	 */
	private static final String linkCheckRegex = "^((https?|ftp)://|(www|ftp)\\.)[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";
	
	@Logger Log log;
	
	@In(create = true)
	FolderHome folderHome;

	public void setLinkIdLink(Integer id) {
		setId(id);
	}

	public Integer getLinkIdLink() {
		return (Integer) getId();
	}

	@Override
	protected Link createInstance() {
		Link link = new Link();
		return link;
	}

	public void load() {
		if (isIdDefined()) {
			wire();
		}
	}

	public void wire() {
		getInstance();
		Folder folderBean = folderHome.getDefinedInstance();
		if (folderBean != null) {
			getInstance().setFolderBean(folderBean);
		}
	}

	public boolean isWired() {
		if (getInstance().getFolderBean() == null)
			return false;
		return true;
	}

	public Link getDefinedInstance() {
		return isIdDefined() ? getInstance() : null;
	}
	
	public String persist() {
		//TODO: Find a way to prevent a wrong link
		String bla = super.persist();
		log.info("Persist Link: " + bla);
		return bla;
	}
	
	public String update() {
		String bla = super.update();
		log.info("Update Link: " + bla);
		return bla;
	}
	
	/**
	 * Verifies the given string if it is an url or not. This ejb is working
	 * with a regular expression for url's.
	 * 
	 * That the string can be recognized as an url, the following rules are
	 * important: - The url can start with the following strings: "http://",
	 * "https://", "www." - The url cant end with a "."
	 * 
	 * @param link
	 *            String to verify
	 * 
	 * @return true: Link is an url / false: Link is not an url
	 */
	public boolean verifyLinkEJB(String link) {

		/* create pattern*/
		Pattern p = Pattern.compile(linkCheckRegex);

		/* get matcher */
		Matcher m = p.matcher(link);

		/* try to find if there is a correct url */
		if (m.find()) 
			return true;
		else
			return false;
   }


}
